import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Route } from '@angular/router';
import { EInvoiceService } from 'src/app/service/fee-enquiry/e-invoice.service';
import { FeeEnquiryService } from 'src/app/service/fee-enquiry/fee-enquiry.service';
import { MessageService } from 'src/app/service/message.service';
import { UsageCodeData, UserBindService } from 'src/app/service/user-bind.service';
import { test_data } from './test-data';
import { NzImageService } from 'ng-zorro-antd/image';
import { downFile } from 'src/app/utils/utils';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-pay-list',
  templateUrl: './pay-list.component.html',
  styleUrls: ['./pay-list.component.scss']
})
export class PayListComponent implements OnInit {

  invflagState = {
    'N': { value: '未开票', color: 'orange' },
    'Y': { value: '已开票', color: 'green' },
  }
  title = '缴费记录'
  constructor(
    private userBind: UserBindService,
    private feeEnquiry: FeeEnquiryService,
    private message: MessageService,
    private route: ActivatedRoute,
    private eInvoice: EInvoiceService,
    private image: NzImageService,
    private http: HttpClient
  ) { }

  usageCode = ''
  address: string | undefined = ''
  ngOnInit(): void {
    this.route.data.subscribe(res => {
      this.title = res['breadcrumb']
      this.getUsageCodeList()
    })
  }

  usageCodeLoading = false
  usageCodeInfoList: UsageCodeData[] = []
  onUsageCodeChange(value: string){
    this.usageCode = value
    this.address = this.usageCodeInfoList.find(_ => _.usageCode === value)?.address
    this.getPayList()
  }
  getUsageCodeList(){
    this.usageCodeLoading = true;
    this.userBind._getBindList().subscribe({
      next: res => {
        this.usageCodeInfoList = res;
        this.initUsageCode(res[0]);
        this.usageCodeLoading = false;
      }, 
      error: error => {
        // this.util.createErrorMessage(error);
        this.usageCodeLoading = false;
      }}
    )
  }
  initUsageCode(item: UsageCodeData){
    this.usageCode = item.usageCode;
    this.address = item.address;
    this.getPayList();
  }

  // private String id;//繳費id
  // private String orderNo;//訂單編號
  // private String userId;//用戶id
  // private String usageCode;//用户编号
  // private String amount;//金額
  // private String payTime;//支付時間
  // private String typeId;//支付類型
  // private String typeName;//类型名称
  // private String payPOS;//商戶編號
  // private String payResult;//支付結果
  // private String resultMsg;//充值結果反饋
  // private String resultNo;//支付流水
  // private String goodsName;//商品名稱
  // private String chargeAmount;//充值金额
  // private Map sourceBillId;//源單據id
  // private String businessType;//業務類型
  // private String month;//支付账单的发单月份
  payTypeEnum = { 
    cash: '现金',
    transferAccount: '转账',
    pos: 'pos机',
    prepayDeduction: '预付费抵扣',
    payOnline: '网厅缴费',
    liveExpense: '生活缴费',
    weChatApplet: '微信小程序',
    aliPayApplet: '支付宝小程序'
  }
  cols = {
    "month":	"发单月份",
    "orderNo":	"订单编号",
    "payTime":	"支付时间",
    "typeId":	"支付方式",
    "amount":	"实收金额",
    "shouldPayAmount":	"应收金额",
  }
  data: any[] = []
  dataLoading = false
  pageNumber = 1
  pageSize = 10
  total = 0
  getPayList(){
    this.dataLoading = true
    this.data = []
    // '00034987'
    this.feeEnquiry._getPayList(this.usageCode, this.pageNumber, this.pageSize).subscribe({
      next: res => {
        if(res && res.resultList){
          this.data = res.resultList
          this.total = res.totalNumber
        }
        this.dataLoading = false
      },
      error: error => {
        this.message.error('查询数据错误, 请稍后再试')
        this.dataLoading = false
      }
    })
  }

  goEInvoice(data: any){
    this.dataLoading = true
    this.eInvoice._applyEInvoice(data.pid, this.usageCode).subscribe({
      next: res => {
        console.log(res)
        this.dataLoading =false
      },
      error: error => {
        this.message.createErrorMessage(error)
        this.dataLoading = false
      }
    })
  }

  invoiceUrl = ''
  downloadUrl = ''
  invoiceModal = false
  viewInvoice(data: any){
    this.dataLoading = true
    this.eInvoice._applyEInvoice(data.pid, this.usageCode).subscribe({
      next: res => {
        console.log(res)
        if(res && res['data'] && res['data']['rtnMsg'] === '开票成功'){
          const invoiceUrl = res['data']['urls'][0]['downpath']
          const baseUrl = '/api/gsxmcp/cs/iv/v1.0/invoice/downloadInvoice?billid=null&pdfUrl='
          this.downloadUrl = baseUrl + invoiceUrl
          this.invoiceUrl = encodeURIComponent(baseUrl + invoiceUrl)
          this.invoiceModal = true
        }else{
          this.message.error(res['data']['rtnMsg'])
        }
        this.dataLoading = false
      },
      error: error => {
        this.message.createErrorMessage(error)
        this.dataLoading = false
      }
    })
  }
  downInvoice(){
    this.dataLoading = true
    this.http.get(this.downloadUrl, { responseType: 'blob' }).subscribe(res => {
      this.dataLoading = false
      downFile(res, '水费电子发票.pdf')
    }, error => {
      this.message.error(error)
      this.dataLoading = false
    })
  }

}
